package com.happymall.demo2.controller;

import com.happymall.demo2.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/loginUser")
    public String loginUser(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {
        // 1、将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        // 2、获取Subject实例对象
        Subject subject = SecurityUtils.getSubject();
        try {
            // 3、认证
            subject.login(usernamePasswordToken);   //完成登录，传到MyAuthorizingRealm类中的方法进行认证
            User user = (User) subject.getPrincipal();
            session.setAttribute("user", user);
            return "index";
        } catch (Exception e) {
            return "login";//返回登录页面
        }
    }

    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "login";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized() {
        return "unauthorized";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/")
    public String home() {
        return "home";
    }

    @RequestMapping("/a/admin")
    @ResponseBody
    public String test2(HttpSession session) {
        return "admin success";
    }

    @RequestMapping("/a/both")
    @ResponseBody
    public String test3(HttpSession session) {
        return "both success";
    }

    @RequestMapping("/b/both")
    @ResponseBody
    public String test4(HttpSession session) {
        return "b success";
    }
}
